package com.relax.mybatis.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import lombok.extern.slf4j.Slf4j;

/**
 * @author relax
 * @date 2022/07/06
 * @desc 插件工具类
 */
@Slf4j
public class PluginUtil {

    /**
     * 获取多层代理下真正的处理对象
     * 
     * @param <T>
     * @param target
     * @return
     */
    public static <T> T getRealTarget(Object target) {
        if (Proxy.isProxyClass(target.getClass())) {
            MetaObject metaObject = SystemMetaObject.forObject(target);
            return getRealTarget(metaObject.getValue("h.target"));
        }
        return (T)target;
    }

    /**
     * 获取类声明的字段，非静态以及transient字段
     * 
     * @param clazz
     * @return
     */
    public static List<Field> getDeclaredFields(Class<?> clazz) {
        if (null == clazz)
            return null;
        Field[] arrayOfField = clazz.getDeclaredFields();
        List<Field> list1 = Arrays.stream(arrayOfField)
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .filter(field -> !Modifier.isTransient(field.getModifiers()))
                .collect(Collectors.toList());
        Class superClass = clazz.getSuperclass();
        if (superClass.equals(Object.class))
            return list1;
        List<Field> list2 = getDeclaredFields(superClass);
        for (Field field : list2) {
            if (!list1.stream().anyMatch(field2 -> field2.getName().equals(field.getName())))
                list1.add(field);
        }
        return list1;
    }

    /**
     * 是否写操作
     * 
     * @param commandType
     * @return
     */
    public static boolean isWriteCommand(SqlCommandType commandType) {
        return SqlCommandType.UPDATE.equals(commandType) || SqlCommandType.INSERT.equals(commandType);
    }

    /**
     * 读取属性
     * 
     * @param obj
     * @param field
     * @return
     */
    public static Object getPropertyValue(Object obj, Field field) {
        Object value = null;
        try {
            value = FieldUtils.readField(field, obj, true);
        } catch (Exception e) {
            log.warn("读取对象属性失败:{}.{}", obj.getClass().getName(), field.getName());
        }
        return value;
    }

    /**
     * 写入属性
     * 
     * @param obj
     * @param field
     * @param value
     */
    public static void setPropertyValue(Object obj, Field field, Object value) {
        try {
            FieldUtils.writeField(field, obj, value, true);
        } catch (Exception e) {
            log.warn("写入对象属性失败:{}.{}", obj.getClass().getName(), field.getName());
        }
    }

}
